capture program drop randomization_table
program define randomization_table, eclass
	/*	The following program is meant to provide the results from "reg <depvar> <variable>, <condlist>" for every <variable> in <varlist>.
		It then exports the results in e() as if it were a regression to be able to create a nice estout table. 	*/
		
	syntax varlist [if/] [in], TMTVAR(varname) GROUPS(numlist) ///
			[CONTrols(string asis)]
	
	//marksample touse
	if "`if'" == "" {
		local if "1==1"
	}
	
	if `"`controls'"' == "" {
		local controls " "
	}
	local ncont = 0
	while `"`controls'"' != "" {
		local ++ncont
		gettoken cont`ncont' controls: controls
	}
	
	//Create temporary variables
	local grplist `groups'
	tempname nbobs 
	local matlist "`matlist' nbobs"
	foreach grp of numlist `groups' {
		tempname mean`grp' sd`grp' n`grp'
		local matlist "`matlist' mean`grp' sd`grp' n`grp'"
		gettoken dump grplist: grplist
		forvalues x = 1/`ncont' {
			foreach grp2 in `grplist' {
				tempname diff_`grp'V`grp2'_mod`x' se_`grp'V`grp2'_mod`x' p_`grp'V`grp2'_mod`x'
				local matlist "p_`grp'V`grp2'_mod`x' se_`grp'V`grp2'_mod`x' diff_`grp'V`grp2'_mod`x' `matlist'"
			}	
		}
	}
	tempname est_b est_V
	tempvar treat sample
	
	gen `treat' = 0
	gen `sample' = 0

	foreach var of local varlist {
		di "`var'"
		summarize `var' if `tmtvar'<. & `if' `in' 
		mat `nbobs'	   = nullmat(`nbobs'), r(N)
		//MEANS OF EACH GROUP
		foreach grp of numlist `groups' {
			summarize `var' if `tmtvar' == `grp' & `if' `in'
			mat `mean`grp''    = nullmat(`mean`grp'') , r(mean)
			mat `sd`grp''      = nullmat(`sd`grp'')   , r(sd)
			mat `n`grp''	   = nullmat(`n`grp'')    , r(N)	
		}

		
		
		local grplist `groups'

		
		foreach grp of numlist `groups' {
			gettoken dump grplist: grplist
			foreach grp2 in `grplist' {

				replace `treat' = (`tmtvar' == `grp')
				replace `sample' = (`tmtvar' == `grp' | `tmtvar' == `grp2')
				
				forvalues x = 1/`ncont' {
					reg `var' `treat' `cont`x'' if `sample'  & `if' `in'

					*Save results from regression
					mat `est_b' = e(b)
					mat `est_V' = e(V)
					
					test `treat' == 0
					
					
					*Construct the fake "regression matrixes" which look like the results from a normal reg function
					mat `diff_`grp'V`grp2'_mod`x'' = nullmat( `diff_`grp'V`grp2'_mod`x'' ), `est_b'[1,1]
					mat `se_`grp'V`grp2'_mod`x''   = nullmat(`se_`grp'V`grp2'_mod`x''  )  , `=sqrt(`est_V'[1,1])'
					mat `p_`grp'V`grp2'_mod`x''    = nullmat(`p_`grp'V`grp2'_mod`x'' )    , `=r(p)'					
				}
			}
		}
	}
	
	*Label the output matricies
	foreach mat in `matlist'{
		 mat coln ``mat'' = `varlist'
		 //mat rown ``mat'' = `depvar'
	 }
	 
	 *Return the results in e() to be read by eststo. 
	 eret post
	 eret local cmd "randomization_table"
	 ereturn local matlist "`matlist'"
	 foreach mat in `matlist' {
		 eret mat `mat' = ``mat''
	 }
	
end
